<?php
namespace app\common\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtService
{
    protected $key;
    protected $alg = 'HS256';
    protected $ttl = 7200; // 2小时

    public function __construct()
    {
        $this->key = env('JWT.SECRET_KEY', 'your_default_key');
        $this->ttl = (int)env('JWT.TTL', 7200);
    }

    /**
     * 生成Token
     * @param int $userId
     * @return string
     */
    public function generateToken(int $userId): string
    {
        $payload = [
            'uid' => $userId,
            'iat' => time(),
            'exp' => time() + $this->ttl
        ];
        return JWT::encode($payload, $this->key, $this->alg);
    }

    /**
     * 验证并解析Token
     * @param string $token
     * @return array|false
     */
    public function verifyToken(string $token)
    {
        try {
            $decoded = JWT::decode($token, new Key($this->key, $this->alg));
            return (array)$decoded;
        } catch (\Exception $e) {
            return false;
        }
    }
}